<?php
/**
 * класс статистики
 *
 */
class Statistics{
	/*
	event_type:
	0 - добавление коммента
	1 - выставление оценки
	2 - выставление сложности
	3 - голосование +/-
	4 - добавление статьи
	5 - добавление урока самоучителя
	6 - добавление ответа
	7 - добавление вопроса
	8 - добавление готового решения
	98 - регистрация человека
	99 - добавление раздела в дерево
	
	sort_type:
	0 - каждый час
	1 - каждый день
	2 - каждую неделю
	3 - каждый месяц
	*/
	
	public static function getStatistics(){
		$objDB = Service_Database::instance();
		$stmt = "
		SELECT *
		FROM `statistics`";
		return $objDB->selectOne($stmt);
	}
	
	/**
	 * получаем статистику задень, обновляемую каждые 5 минут
	 *
	 */
	public static function getNowDayStatistics(){
		$objDB = Service_Database::instance();
		$stmt = "
		SELECT *
		FROM `statistics_sort`
		WHERE `statistics_sort`.`sort_type` = 0
		ORDER BY `statistics_sort`.`datetime` DESC
		LIMIT 1";
		return $objDB->selectOne($stmt);
	}	
	
	/**
	 * получаем статистику по типу
	 *
	 */
	public static function getNumDayStatistics($num, $limit = 10){
		$objDB = Service_Database::instance();
		$stmt = "
		SELECT *
		FROM `statistics_sort`
		WHERE `statistics_sort`.`sort_type` = " . $num . "
		ORDER BY `statistics_sort`.`datetime` DESC
		LIMIT 0, " . $limit;
		$array = $objDB->select($stmt);
		$array = array_reverse($array);
		return $array;
	}	
	
	/**
	 * добавление нового события 
	 *
	 */
	public static function addEvent($event_type, $idUser){
//		if ($event_type <= 8) self::addEventToUser($event_type, $idUser); // не сдлеано
		$objDB = Service_Database::instance();
		$stmt = "
		INSERT INTO `".DB_PREFIX."statistics_log` (`".DB_PREFIX."statistics_log`.`id_user`, 
																	`".DB_PREFIX."statistics_log`.`event_type`,
																	`".DB_PREFIX."statistics_log`.`datetime`)
		VALUES (" . $idUser . ", " . $event_type . ", '" . Service_Date::gLocalTime2BD() . "')";
		$objDB->query($stmt);
		
		$stmt = "
		UPDATE `".DB_PREFIX."statistics` 
			SET `".DB_PREFIX."statistics`.`" . self::getEventType($event_type) . "` = (`".DB_PREFIX."statistics`.`" . self::getEventType($event_type) . "` + 1)";
		$objDB->query($stmt);
		return true;
	}
	
	/**
	 * инкремент соответсвующего поля в таблице user
	 */
	public static function addEventToUser($event_type, $idUser){
		switch ($event_type){
			case 0: $field = 'comment_amount'; break;
			case 1: $field = 'set_mark_amount'; break;
			case 2: $field = 'difficulty_mark_amount'; break;
			case 3: $field = 'voting_amount'; break;
			case 4: $field = 'article_amount'; break;
			case 5: $field = 'lesson_amount'; break;
			case 6: $field = 'answer_amount'; break;
			case 7: $field = 'question_amount'; break;
			case 8: $field = 'solution_amount'; break;
		}
	}
	
	/**
	 * получаем имя сущности по её номеру
	 */
	private static function getEventType($event_type){		
		switch ($event_type){
			case 0: return 'comment'; break;
			case 1: return 'mark'; break;
			case 2: return 'difficulty'; break;
			case 3: return 'voting'; break;
			case 4: return 'article'; break;
			case 5: return 'lesson'; break;
			case 6: return 'answer'; break;
			case 7: return 'question'; break;
			case 8: return 'solution'; break;
			case 98: return 'user'; break;
			case 99: return 'tree_section'; break;
		}
	}
	
	/**
	 * пересчет полей и сохранение за час
	 */
	public static function statisticsSaveDayEveryHour(){
		
		$objDB = Service_Database::instance();
		$stmt = "
		SELECT `statistics_log`.`event_type`, COUNT(`statistics_log`.`event_type`) as `field`
		FROM `statistics_log`
		WHERE `statistics_log`.`datetime` <= '" . Service_Date::gLocalTime2BD() . "' AND 
					`statistics_log`.`datetime` >= '" . gmdate("Y-m-d H:i:s", time() - 3600) . "'
		GROUP BY `statistics_log`.`event_type`";
		$arrStatistics = $objDB->select($stmt);
		self::addInStatSort($arrStatistics, 0);
		return $arrStatistics;
	}
	/**
	 * пересчет полей и сохранение за 24 часа
	 */
	public static function statisticsSaveEveryDay(){
		
		$objDB = Service_Database::instance();
		$stmt = "
		SELECT `statistics_log`.`event_type`, COUNT(`statistics_log`.`event_type`) as `field`
		FROM `statistics_log`
		WHERE `statistics_log`.`datetime` <= '" . Service_Date::gLocalTime2BD() . "' AND 
					`statistics_log`.`datetime` >= '" . gmdate("Y-m-d H:i:s", time() - 86400) . "'
		GROUP BY `statistics_log`.`event_type`";
		$arrStatistics = $objDB->select($stmt);
		self::addInStatSort($arrStatistics, 1);
		return $arrStatistics;
	}
	
	/**
	 * пересчет полей и сохранение каждую неделю
	 */
	public static function statisticsSaveEveryWeek(){
		
		$objDB = Service_Database::instance();
		$stmt = "
		SELECT `statistics_log`.`event_type`, COUNT(`statistics_log`.`event_type`) as `field`
		FROM `statistics_log`
		WHERE `statistics_log`.`datetime` <= '" . Service_Date::gLocalTime2BD() . "' AND 
					`statistics_log`.`datetime` >= '" . gmdate("Y-m-d H:i:s", time() - 604800) . "'
		GROUP BY `statistics_log`.`event_type`";
		$arrStatistics = $objDB->select($stmt);
		self::addInStatSort($arrStatistics, 2);
		return $arrStatistics;
	}
	
	/**
	 * пересчет полей и сохранение каждый месяц
	 */
	public static function statisticsSaveEveryMonth(){
		
		$objDB = Service_Database::instance();
		$stmt = "
		SELECT `statistics_log`.`event_type`, COUNT(`statistics_log`.`event_type`) as `field`
		FROM `statistics_log`
		WHERE `statistics_log`.`datetime` <= '" . Service_Date::gLocalTime2BD() . "' AND 
					`statistics_log`.`datetime` >= '" . gmdate("Y-m-d H:i:s", time() - 18385920) . "'
		GROUP BY `statistics_log`.`event_type`";
		$arrStatistics = $objDB->select($stmt);
		self::addInStatSort($arrStatistics, 3);
		return $arrStatistics;
	}
	
	/**
	 * вставка данных статистики в таблицу statistics_sort
	 *
	 * @param $type тип выборки(за день, за сутки, месяц)
	 */
	public static function addInStatSort($arrStatistics, $type){
		$objDB = Service_Database::instance();
		
		foreach ($arrStatistics as $value)
			$arrStat[$value['event_type']] = $value['field'];	
			
		$stmt = "
		INSERT INTO `statistics_sort` (`statistics_sort`.`datetime`,
																	 `statistics_sort`.`sort_type`,
																	 `statistics_sort`.`comment`,
																	 `statistics_sort`.`mark`,
																	 `statistics_sort`.`difficulty`,
																	 `statistics_sort`.`voting`,
																	 `statistics_sort`.`article`,
																	 `statistics_sort`.`lesson`,
																	 `statistics_sort`.`answer`,
																	 `statistics_sort`.`question`,
																	 `statistics_sort`.`solution`,
																	 `statistics_sort`.`user`,
																	 `statistics_sort`.`tree_section`)
		VALUES ('" . Service_Date::gLocalTime2BD() . "',
						" . $type . ",
						" . (isset($arrStat[0]) ? $arrStat[0] : "NULL") . ",
						" . (isset($arrStat[1]) ? $arrStat[1] : "NULL") . ",
						" . (isset($arrStat[2]) ? $arrStat[2] : "NULL") . ",
						" . (isset($arrStat[3]) ? $arrStat[3] : "NULL") . ",
						" . (isset($arrStat[4]) ? $arrStat[4] : "NULL") . ",
						" . (isset($arrStat[5]) ? $arrStat[5] : "NULL") . ",
						" . (isset($arrStat[6]) ? $arrStat[6] : "NULL") . ",
						" . (isset($arrStat[7]) ? $arrStat[7] : "NULL") . ",
						" . (isset($arrStat[8]) ? $arrStat[8] : "NULL") . ",
						" . (isset($arrStat[98]) ? $arrStat[98] : "NULL") . ",
						" . (isset($arrStat[99]) ? $arrStat[99] : "NULL") . "
		)";
		return $objDB->query($stmt);
	}
	
	public static function getStatisticForIndex(){
		$objDB = Service_Database::instance();
		$date = Service_Date::filterDateBD(date('d.m.Y'));
		$stmt = "
		SELECT COUNT(`article`.`ID_article`) as `article`
		FROM `article`
		WHERE `article`.`creation` >= '" . $date . "' AND `delete_flag` = 1 AND `article`.`draft` = 0";
		$arrNew['article'] = $objDB->selectSimpleField($stmt);
		
		$stmt = "
		SELECT COUNT(`question`.`ID_question`) as `question`
		FROM `question`
		WHERE `question`.`creation` >= '" . $date . "'";
		$arrNew['question'] = $objDB->selectSimpleField($stmt);
		
		$stmt = "
		SELECT COUNT(`solution`.`ID_solution`) as `solution`
		FROM `solution`
		WHERE `solution`.`creation` >= '" . $date . "'";
		$arrNew['solution'] = $objDB->selectSimpleField($stmt);
		
		$stmt = "
		SELECT COUNT(`tutorial_lesson`.`ID_tutorial_lesson`) as `lesson`
		FROM `tutorial_lesson`
		WHERE `tutorial_lesson`.`creation` >= '" . $date . "'";
		$arrNew['lesson'] = $objDB->selectSimpleField($stmt);
		
		return $arrNew;
	}
}
?>